package top.kaoshanji.p3ch12a;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p3ch12a-228页a：处理登录
 * 用户骂和密码必须为 ken/secret
 * @author kaoshanji
 * ^_^
 * create time 2025/4/9 10:40
 */
@WebServlet(urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = -920L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        if (userName != null && userName.equals("ken") && password != null && password.equals("secret")) {
            HttpSession session = req.getSession(true);
            session.setAttribute(Constant.HTTPSESSION_ATTRIBUTE_LOGGED, Boolean.TRUE);

            resp.sendRedirect("download"); // 重定向..服务器内部完成
            return;
        } else {
            RequestDispatcher dispatcher = req.getRequestDispatcher(Constant.JSP_LOGIN);
            dispatcher.forward(req, resp); // 请求转发...浏览器完成...都见到了....
        }

    }

}
